package net.wanho.service.impl;

import lombok.SneakyThrows;
import net.wanho.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
    //本地文件上传路径
    @Value("${file.path}")
    private String localFilePath;

    //本地文件上传前缀
    @Value("${file.prefix}")
    private String localFilePrefix;

    @Value("${file.domain}")
    private String domain;
    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        //拼接文件上传路径
        String uploadDir= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String fileName=file.getOriginalFilename();
        fileName= UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        File uploadPath=new File(localFilePath+ File.separator+uploadDir+File.separator+fileName);

        //判断文件目录是否存在
        if(!uploadPath.getParentFile().exists()){
            uploadPath.getParentFile().mkdir();
        }

        //保存文件
        file.transferTo(uploadPath);

        //拼接文件访问路径
        String url=localFilePrefix+"/"+uploadDir+"/"+fileName;

        return url;
    }
}
